package com.itic.mobile.yhlm;



import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.mobile.base.BaseMobileInterface;
import com.itic.system.jdlmsetting.persistence.model.JdlmSetting;
import com.itic.system.jdlmsetting.service.JdlmSettingService;
import com.jd.open.api.sdk.DefaultJdClient;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.request.cps.ServicePromotionCouponGetCodeBySubUnionIdRequest;
import com.jd.open.api.sdk.request.cps.ServicePromotionWxsqGetCodeBySubUnionIdRequest;
import com.jd.open.api.sdk.response.cps.ServicePromotionCouponGetCodeBySubUnionIdResponse;
import com.jd.open.api.sdk.response.cps.ServicePromotionWxsqGetCodeBySubUnionIdResponse;

import net.sf.json.JSONObject;


/**
 * 京东联盟
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "/mobile/yhlm")
public class YhlmInterface extends BaseMobileInterface {
	
	/**
	 * 默认的京东联盟账号
	 * 	 友惠家公司
	 * */
	private static String url = "https://api.jd.com/routerjson";
	private static String unionId = "1000169071";
	private static String key = "23D0D64434349441EB49DA44F13EDB69";
	private static String secret = "857472d299d84727a7d021ae40d3bc8b";
	private static String accesstoken = "81e08619-d5be-43a9-9eb5-81746dcc52a5";
	
	@Autowired
	private JdlmSettingService jdlmSettingService;
	
	/**
	 * 初始化京东联盟配置信息
	 * @param unionid
	 * unionid 1000466519
	 * key 758E9DE6C40A4C97C3195D1E383E41BE
	 * secret 50176e262f10453d97ce5fba2918dc3d
	 * access_token 8de91341-9d1d-4216-95bf-4e8bc7f82454
	 * position 1091396120
	 */
	@RequestMapping(value = "/getUrl")
	@ResponseBody
	public Map<String, Object> getUrl( HttpServletRequest request, HttpServletResponse response, String uid, String pid, String sku ) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		
		try{
			JdlmSetting jdlmSetting = new JdlmSetting();
			
			jdlmSetting.setAccessToken(accesstoken);
			jdlmSetting.setAppKey(key);
			jdlmSetting.setSecket(secret);
			jdlmSetting.setUnionId(unionId);
			
			if( StringHelper.isNotBlank(uid) ){
				jdlmSetting = jdlmSettingService.getJdSettingByUnionId(uid);
			}
			
			JdClient client=new DefaultJdClient(url,jdlmSetting.getAccessToken(),jdlmSetting.getAppKey(),jdlmSetting.getSecket());
			//如果红包卷链接为空，则进入普通转链
			ServicePromotionWxsqGetCodeBySubUnionIdRequest requestJd = new ServicePromotionWxsqGetCodeBySubUnionIdRequest();
	   		requestJd.setProCont( 1 ); //推广内容：1单品
	   		requestJd.setMaterialIds(sku); //推广物料：单品skuId
	   		requestJd.setSubUnionId(jdlmSetting.getUnionId());
	   		if( StringHelper.isNotBlank(pid) ){
	   			requestJd.setPositionId(Long.parseLong(pid));
	   		}
	   		
	   		
	   		ServicePromotionWxsqGetCodeBySubUnionIdResponse responseJd = client.execute(requestJd);
	   		
	   		//解析返回参数
	   		if( "0".equals(responseJd.getCode()) ){
	   			String result2 = responseJd.getGetcodebysubunionidResult();
	   			if( result2.contains("urlList") ){
	   				JSONObject fromObject = JSONObject.fromObject(result2);
	   				JSONObject jsonObject = fromObject.getJSONObject("urlList");
	   				String unionSkuUrl = jsonObject.getString(sku);
	   				resultMap.put(DATA, unionSkuUrl);
	   				errorCode = SUCCESS_ERROR_CODE;
	   				errorMsg = SUCCESS_ERROR_MSG;
	   			}else{
	   				errorCode = CON_NULL_ERROR_CODE;
	   				errorMsg = CON_NULL_ERROR_MSG;
	   			}
	   		}else{
				errorCode = CON_NULL_ERROR_CODE;
   				errorMsg = CON_NULL_ERROR_MSG;
	   		}
		}catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("JdlmInterface", "getUrl", e.toString(), "京东联盟普通二合一转链接", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}
	
	
	
	
	/**
	 * 初始化京东联盟配置信息
	 * @param unionid
	 * unionid 1000466519
	 * key 758E9DE6C40A4C97C3195D1E383E41BE
	 * secret 50176e262f10453d97ce5fba2918dc3d
	 * access_token 8de91341-9d1d-4216-95bf-4e8bc7f82454
	 * position 1091396120
	 */
	@RequestMapping(value = "/test")
	@ResponseBody
	public Map<String, Object> test( String sku, String conUrl ) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			String encode = URLEncoder.encode("http://coupon.m.jd.com/coupons/show.action?key=faa8d83af02c41aabdf1823c95264179&roleId=9547553&to=mall.jd.com/index-186091.html","GBK");
			String sendPost = HttpRequestUtils.sendPost("http://192.168.1.125:8090/ddt/mobile/jdlm/getConUrl", "sku=21677689636&conUrl="+encode);
			System.out.println(sendPost);
		}catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("JdlmInterface", "getConUrl", e.toString(), "京东联盟优惠券二合一转链接", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}
	
	/**
	 * 初始化京东联盟配置信息
	 * @param unionid
	 * unionid 1000466519
	 * key 758E9DE6C40A4C97C3195D1E383E41BE
	 * secret 50176e262f10453d97ce5fba2918dc3d
	 * access_token 8de91341-9d1d-4216-95bf-4e8bc7f82454
	 * position 1091396120
	 */
	@RequestMapping(value = "/getConUrl")
	@ResponseBody
	public Map<String, Object> getConUrl( String uid, String pid, String sku, String conUrl ) throws Exception{
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		String errorCode = PARAM_ERROR_CODE;
		String errorMsg = PARAM_ERROR_MSG;
		try{
			JdlmSetting jdlmSetting = new JdlmSetting();
			
			jdlmSetting.setAccessToken(accesstoken);
			jdlmSetting.setAppKey(key);
			jdlmSetting.setSecket(secret);
			
			if( StringHelper.isNotBlank(uid) ){
				jdlmSetting = jdlmSettingService.getJdSettingByUnionId(uid);
			}
			
			JdClient client=new DefaultJdClient(url,jdlmSetting.getAccessToken(),jdlmSetting.getAppKey(),jdlmSetting.getSecket());
			
			ServicePromotionCouponGetCodeBySubUnionIdRequest requestJd = new ServicePromotionCouponGetCodeBySubUnionIdRequest();
			
			conUrl = conUrl.replace("&amp;", "&");
			requestJd.setCouponUrl( conUrl );
			requestJd.setMaterialIds( sku );
			requestJd.setSubUnionId( jdlmSetting.getUnionId() );
			if( StringHelper.isNotBlank(pid) ){
				requestJd.setPositionId( Long.parseLong(pid) );
			}
			
	   		ServicePromotionCouponGetCodeBySubUnionIdResponse responseJd = client.execute(requestJd);
	   		//解析返回参数
	   		if( "0".equals(responseJd.getCode()) ){
	   			String result2 = responseJd.getGetcodebysubunionidResult();
	   			if( result2.contains("urlList") ){
	   				JSONObject fromObject = JSONObject.fromObject(result2);
	   				JSONObject jsonObject = fromObject.getJSONObject("urlList");
	   				String unionSkuUrl = jsonObject.getString(conUrl+","+sku);
	   				
	   				if( StringHelper.isNotBlank(unionSkuUrl) ){
	   					resultMap.put(DATA, unionSkuUrl);
		   				errorCode = SUCCESS_ERROR_CODE;
		   				errorMsg = SUCCESS_ERROR_MSG;
	   				}else{
	   					errorCode = CON_NULL_ERROR_CODE;
		   				errorMsg = CON_NULL_ERROR_MSG;
	   				}
	   			}else{
	   				resultMap.put(DATA, result2);
   					errorCode = CON_NULL_ERROR_CODE;
	   				errorMsg = CON_NULL_ERROR_MSG;
	   			}
	   		}else{
	   			resultMap.put(DATA, responseJd.getGetcodebysubunionidResult());
   				errorCode = SUCCESS_ERROR_CODE;
   				errorMsg = SUCCESS_ERROR_MSG;
	   		}
		}catch (Exception e) {
			errorCode = SERVER_ERROR_CODE;
			errorMsg = SERVER_ERROR_MSG;
			logException("JdlmInterface", "getConUrl", e.toString(), "京东联盟优惠券二合一转链接", e);
		}
		resultMap.put(CODE, errorCode);
		resultMap.put(MSG, errorMsg);
		return resultMap;
	}
	
	
	
	
	
	/**
	 * 
	 * public JdClient client=new DefaultJdClient(SERVER_URL,accessToken,appKey,appSecret);
	 * https://oauth.jd.com/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&
		redirect_uri=YOUR_REGISTERED_REDIRECT_URI&state=YOUR_CUSTOM_CODE
	 */
	@RequestMapping(value = "/getCode")
	@ResponseBody
	public JSONObject getCode( String key){
		String url = "https://oauth.jd.com/oauth/authorize?response_type=code&client_id="+key+"&redirect_uri=http://www.jhjvip.cn&state=code";
		return HttpRequestUtils.httpGet(url);
	}
	
	/**
	 * https://oauth.jd.com/oauth/token?grant_type=authorization_code&client_id=758E9DE6C40A4C97C3195D1E383E41BE&
redirect_uri=http://www.jhjvip.cn&code=2o5nGz&state=code&client_secret=50176e262f10453d97ce5fba2918dc3d
       
	 */
	@RequestMapping(value = "/getAccessToken")
	@ResponseBody
	public String getAccessToken( String code, String key, String secret ){
		String result = "";
		try{
			String urlTemp = "https://oauth.jd.com/oauth/token";
			JSONObject obj = new JSONObject();
	        obj.element("grant_type", "authorization_code");
	        obj.element("client_id", key);
	        obj.element("redirect_uri", "http://www.jhjvip.cn");
	        obj.element("code", code);
	        obj.element("state", "code");
	        obj.element("client_secret", secret);
	        //创建连接
	        URL url = new URL(urlTemp);
	        HttpURLConnection connection = (HttpURLConnection) url
	                .openConnection();
	        connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setRequestMethod("POST");
	        connection.setUseCaches(false);
	        connection.setInstanceFollowRedirects(true);
	        connection.setRequestProperty("Content-Type",
	                "application/x-www-form-urlencoded");
	
	        connection.connect();
	
	        //POST请求
	        DataOutputStream out = new DataOutputStream(
	                connection.getOutputStream());
	
	        out.writeBytes(obj.toString());
	        out.flush();
	        out.close();
	
	        //读取响应
	        BufferedReader reader = new BufferedReader(new InputStreamReader(
	                connection.getInputStream()));
	        String lines;
	        StringBuffer sb = new StringBuffer("");
	        while ((lines = reader.readLine()) != null) {
	            lines = new String(lines.getBytes(), "utf-8");
	            sb.append(lines);
	        }
	        result = sb.toString();
	        reader.close();
	        // 断开连接
	        connection.disconnect();
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
		return result;
	}
}